
package com.phevos.usercenter.client.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.phevos.usercenter.client.UserCenterConstant;
import com.phevos.usercenter.client.vo.OrgTypeValue;
import com.phevos.usercenter.client.vo.OrganizationValue;
import com.phevos.usercenter.client.vo.RelOrgUserValue;
import com.phevos.usercenter.client.vo.RelUserGroupValue;
import com.phevos.usercenter.client.vo.UserAttrValue;
import com.phevos.usercenter.client.vo.UserGroupValue;
import com.phevos.usercenter.client.vo.UserValue;

public class Orgnization
{
    private static Logger logger = LoggerFactory.getLogger(Function.class.getName());

    public static CacheManager cacheManager = CacheManager.getInstance();

    /**
     * ͨ���ʻ�����һ��USER
     * 
     * @param account
     * @return
     */
    public static UserValue getUserByAccount(String account)
    {
        Cache userCache = cacheManager.getCache(UserCenterConstant.USERCACHE);
        if (userCache == null)
        {
            logger.error("UserCache cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List userList = getCache(userCache, UserCenterConstant.USER);
        for (int i = 0; i < userList.size(); i++)
        {
            UserValue user = (UserValue)userList.get(i);
            if (user != null && user.getAccount() != null && user.getAccount().equals(account))
            {
                return user;
            }
        }
        return null;
    }

    /**
     * ���һ����֯
     * 
     * @param organizationName
     * @param typeName
     * @return
     */
    public static OrganizationValue getOrganization(String organizationName, String typeName)
    {
        Cache orgCache = cacheManager.getCache(UserCenterConstant.ORGANIZATIONCACHE);
        if (orgCache == null)
        {
            logger.error("ORGANIZATION cache hadn't defined in ehcahe.xml ");
            return null;
        }
        OrgTypeValue orgType = getOrgType(typeName);
        Integer orgId = null;
        if (orgType != null && orgType.getName() != null)
        {
            orgId = orgType.getId();
        }
        else
        {
            return null;
        }
        List orgList = getCache(orgCache, UserCenterConstant.ORGANIZATION);
        for (int i = 0; i < orgList.size(); i++)
        {
            OrganizationValue organization = (OrganizationValue)orgList.get(i);
            if (organization != null && organization.getName() != null && organization.getName().equals(organizationName)
                    && organization.getTypeId().equals(orgId))
            {
                return organization;
            }
        }
        return null;
    }

    public static List getUserFromUserGroupByGroupId(String groupId)
    {
        Cache groupCache = cacheManager.getCache(UserCenterConstant.USERGROUPCACHE);
        if (groupCache == null)
        {
            logger.error("UserGroupCache hadn't in ehcache");
            return null;
        }
        List relUserGroup = getCache(groupCache, UserCenterConstant.RELUSERGROUP);
        if (relUserGroup == null)
        {
            return null;
        }
        HashMap userMap = new HashMap();
        for (int i = 0; i < relUserGroup.size(); i++)
        {
            RelUserGroupValue relUserGroupValue = (RelUserGroupValue)relUserGroup.get(i);
            if (relUserGroupValue.getGroupId() != null && relUserGroupValue.getGroupId().equals(new Integer(groupId)))
            {
                userMap.put(relUserGroupValue.getUserId(), "true");
            }
        }
        List userList = getALlUser();
        if (userList == null)
        {
            return null;
        }
        List resultList = new ArrayList();
        for (int i = 0; i < userList.size(); i++)
        {
            UserValue userValue = (UserValue)userList.get(i);
            if (userMap.containsKey(userValue.getId()))
            {
                resultList.add(userValue);
            }
        }
        return resultList;
    }

    /**
     * ���һ�����µ������û�VO
     * 
     * @param groupName
     * @return
     */
    public static List getUserByGroupName(String groupName)
    {
        Cache groupCache = cacheManager.getCache(UserCenterConstant.USERGROUPCACHE);
        if (groupCache == null)
        {
            logger.error("USERGROUPCACHE  hadn't defined in ehcahe.xml ");
            return null;
        }
        Integer groupId = getUserGroupIdByName(groupCache, groupName);
        if (groupId == null)
        {
            return null;
        }
        List userGrouplist = getCache(groupCache, UserCenterConstant.RELUSERGROUP);
        List userList = new ArrayList();
        for (Iterator iter = userGrouplist.iterator(); iter.hasNext();)
        {
            RelUserGroupValue value = (RelUserGroupValue)iter.next();
            if (value.getGroupId() != null && value.getGroupId().equals(groupId))
            {
                UserValue user = getUserById(value.getUserId());
                if (user != null)
                {
                    userList.add(user);
                }
            }
        }
        return userList;
    }

    /**
     * @param organizationName
     * @param typeName
     * @return
     */
    public static List getUserByOrganization(String organizationName, String typeName)
    {
        OrganizationValue orgValue = getOrganization(organizationName, typeName);
        if (orgValue == null)
        {
            return null;
        }
        Integer orgId = orgValue.getId();
        Cache orgCache = cacheManager.getCache(UserCenterConstant.ORGANIZATIONCACHE);
        List orgUser = getCache(orgCache, UserCenterConstant.ORGUSER);
        List userList = new ArrayList();
        for (Iterator iter = orgUser.iterator(); iter.hasNext();)
        {
            RelOrgUserValue value = (RelOrgUserValue)iter.next();
            if (value != null && value.getOrgId() != null && value.getOrgId().equals(orgId))
            {
                UserValue user = getUserById(value.getUserId());
                if (user != null)
                {
                    userList.add(user);
                }
            }
        }
        return userList;
    }

    public static UserValue getUserById(Integer id)
    {
        Cache userCache = cacheManager.getCache(UserCenterConstant.USERCACHE);
        if (userCache == null)
        {
            logger.error("UserCache cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List userList = getCache(userCache, UserCenterConstant.USER);
        for (int i = 0; i < userList.size(); i++)
        {
            UserValue user = (UserValue)userList.get(i);
            if (user != null && user.getId() != null && user.getId().equals(id))
            {
                return user;
            }
        }
        return null;
    }

    /**
     * @param groupCache
     * @param groupName
     * @return
     */
    private static Integer getUserGroupIdByName(Cache groupCache, String groupName)
    {
        List groupList = getCache(groupCache, UserCenterConstant.USERGROUP);
        Integer groupId = null;
        for (Iterator iter = groupList.iterator(); iter.hasNext();)
        {
            UserGroupValue groupValue = (UserGroupValue)iter.next();
            if (groupValue.getName() != null && groupValue.getName().equals(groupName))
            {
                groupId = groupValue.getId();
            }
        }
        return groupId;
    }

    /**
     * @return
     */
    public static List getALlUser()
    {
        Cache userCache = cacheManager.getCache(UserCenterConstant.USERCACHE);
        if (userCache == null)
        {
            logger.error("UserCache cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List userList = getCache(userCache, UserCenterConstant.USER);
        return userList;
    }

    public static List getALlUserGroup()
    {
        Cache groupCache = cacheManager.getCache(UserCenterConstant.USERGROUPCACHE);
        if (groupCache == null)
        {
            logger.error("UserGroupsCache cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List groupList = getCache(groupCache, UserCenterConstant.USERGROUP);
        return groupList;
    }

    /**
     * @return
     */
    public static List getUserExtAttr()
    {
        Cache userCache = cacheManager.getCache(UserCenterConstant.USERCACHE);
        if (userCache == null)
        {
            logger.error("UserCache cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List userExtAttrList = getCache(userCache, UserCenterConstant.USEREXTATTR);
        return userExtAttrList;
    }

    /**
     * ����û�)չ����
     * 
     * @param userAccount
     * @param userExtAttrId
     * @return
     */
    public static UserAttrValue getUserAttr(String userAccount, Integer userExtAttrId)
    {
        Cache userCache = cacheManager.getCache(UserCenterConstant.USERCACHE);
        if (userCache == null)
        {
            logger.error("UserCache cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List userList = getCache(userCache, UserCenterConstant.USER);
        Integer userId = getUserIdByAccount(userList, userAccount);
        if (userId == null)
        {
            return null;
        }
        List userAttrList = getCache(userCache, UserCenterConstant.USERATTR);
        for (Iterator iter = userAttrList.iterator(); iter.hasNext();)
        {
            UserAttrValue value = (UserAttrValue)iter.next();
            if (userExtAttrId != null && value != null && value.getUserId() != null && value.getAttrId() != null
                    && value.getUserId().equals(userId) && value.getAttrId().equals(userExtAttrId))
            {
                return value;
            }
        }
        return null;
    }

    private static Integer getUserIdByAccount(List userList, String userAccount)
    {
        Integer userId = null;
        for (int i = 0; userList != null && i < userList.size(); i++)
        {
            UserValue userValue = (UserValue)userList.get(i);
            if (userValue.getAccount() != null && userValue.getAccount().equals(userAccount))
            {
                userId = userValue.getId();
                break;
            }
        }
        return userId;
    }

    public static List getOrgAllType()
    {
        Cache orgCache = cacheManager.getCache(UserCenterConstant.ORGANIZATIONCACHE);
        if (orgCache == null)
        {
            logger.error("ORGANIZATION cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List orgList = getCache(orgCache, UserCenterConstant.ORGTYPE);
        return orgList;
    }

    public static OrgTypeValue getOrgType(String typeName)
    {
        Cache orgCache = cacheManager.getCache(UserCenterConstant.ORGANIZATIONCACHE);
        if (orgCache == null)
        {
            logger.error("ORGANIZATION cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List orgList = getCache(orgCache, UserCenterConstant.ORGTYPE);
        for (int i = 0; i < orgList.size(); i++)
        {
            OrgTypeValue orgType = (OrgTypeValue)orgList.get(i);
            if (orgType != null && orgType.getName() != null && orgType.getName().equals(typeName))
            {
                return orgType;
            }
        }
        return null;
    }

    private static List getCache(Cache cache, String constant)
    {
        // List keys = cache.getKeys();
        // for (int i = 0; i < keys.size(); i++) {
        // System.out.println(keys.get(i).toString());
        // }
        Element element = cache.get(constant);
        if (element == null)
        {
            logger.error(constant + " not in cache");
            return new ArrayList();
        }
        List list = (List)element.getObjectValue();
        return list;
    }

    public static List getUserGroupIdsByUserId(Integer userId)
    {
        Cache groupCache = cacheManager.getCache(UserCenterConstant.USERGROUPCACHE);
        if (groupCache == null)
        {
            logger.error("USERGROUPCACHE cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List userGrouplist = getCache(groupCache, UserCenterConstant.RELUSERGROUP);
        List groupList = new ArrayList();
        HashMap groupExist = new HashMap();
        if (userGrouplist != null)
        {
            for (Iterator iter2 = userGrouplist.iterator(); iter2.hasNext();)
            {
                RelUserGroupValue value = (RelUserGroupValue)iter2.next();
                if (value.getUserId() != null && value.getUserId().equals(userId) && value.getGroupId() != null)
                {
                    if (!groupExist.containsKey(value.getGroupId()))
                    {
                        groupList.add(value.getGroupId());
                        groupExist.put(value.getGroupId(), "true");
                    }
                }
            }
        }
        return groupList;
    }

    public static List getUserGroupsByUserId(Integer userId)
    {
        List<Integer> userGroupIdList = getUserGroupIdsByUserId(userId);
        Cache groupCache = cacheManager.getCache(UserCenterConstant.USERGROUPCACHE);
        if (userGroupIdList == null || groupCache == null)
        {
            return null;
        }
        List<UserGroupValue> userGroupList = getCache(groupCache, UserCenterConstant.USERGROUP);
        List groupList = new ArrayList();
        HashMap groupMap = new HashMap<Integer, UserGroupValue>();
        if (userGroupList != null)
        {
            for (int i = 0; i < userGroupList.size(); i++)
            {
                groupMap.put(userGroupList.get(i).getId(), userGroupList.get(i));
            }
            for (int i = 0; i < userGroupIdList.size(); i++)
            {
                groupList.add(groupMap.get(userGroupIdList.get(i)));
            }
        }
        return groupList;
    }

    public static List getOrgnizationsByUserId(Integer userId)
    {
        Cache orgCache = cacheManager.getCache(UserCenterConstant.ORGANIZATIONCACHE);
        if (orgCache == null)
        {
            logger.error("OrgnizationCACHE cache hadn't defined in ehcahe.xml ");
            return null;
        }
        List orgUserList = getCache(orgCache, UserCenterConstant.ORGUSER);
        List orgList = new ArrayList();
        HashMap orgExist = new HashMap();
        if (orgList != null)
        {
            for (Iterator iter = orgUserList.iterator(); iter.hasNext();)
            {
                RelOrgUserValue value = (RelOrgUserValue)iter.next();
                if (value.getUserId() != null && value.getUserId().equals(userId) && value.getOrgId() != null)
                {
                    if (!orgExist.containsKey(value.getOrgId()))
                    {
                        orgList.add(value.getOrgId());
                        orgExist.put(value.getOrgId(), "true");
                    }
                }
            }
        }
        return orgList;
    }

    /**
     * @param groupId
     * @return
     */
    public static UserGroupValue getUserGroupByGroupId(Integer groupId)
    {
        Cache groupCache = cacheManager.getCache(UserCenterConstant.USERGROUPCACHE);
        if (groupCache == null)
        {
            logger.error("GroupCache cache hadn't defined in ehcahe.xml");
            return null;
        }
        List groupList = getCache(groupCache, UserCenterConstant.USERGROUP);
        for (int i = 0; groupList != null && i < groupList.size(); i++)
        {
            UserGroupValue userGroupValue = (UserGroupValue)groupList.get(i);
            userGroupValue.getId();
            if (userGroupValue != null && userGroupValue.getId() != null && userGroupValue.getId().equals(groupId))
            {
                return userGroupValue;
            }
        }
        return null;
    }
}
